package com.linln.common.utils;

import java.util.concurrent.atomic.AtomicInteger;

public class SnowflakeIdGenerator {

    // 起始时间戳（可以根据实际需求调整）
    private final static long START_TIMESTAMP = 1672531200000L; // 2023-01-01 00:00:00

    // 每一部分占用的位数
    private final static long TIMESTAMP_BITS = 41L;
    private final static long DATA_CENTER_ID_BITS = 5L;
    private final static long MACHINE_ID_BITS = 5L;
    private final static long SEQUENCE_BITS = 12L;

    // 最大值计算
    private final static long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS);
    private final static long MAX_MACHINE_ID = ~(-1L << MACHINE_ID_BITS);
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    // 各部分的偏移量
    private final static long MACHINE_ID_SHIFT = SEQUENCE_BITS;
    private final static long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS;
    private final static long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + MACHINE_ID_BITS + DATA_CENTER_ID_BITS;

    // 序列号原子变量
    private AtomicInteger sequence = new AtomicInteger(0);

    // 上一次的时间戳
    private volatile long lastTimestamp = -1L;

    // 数据中心 ID 和机器 ID
    private final long dataCenterId;
    private final long machineId;

    public SnowflakeIdGenerator(long dataCenterId, long machineId) {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("Data Center Id can't be greater than " + MAX_DATA_CENTER_ID + " or less than 0");
        }
        if (machineId > MAX_MACHINE_ID || machineId < 0) {
            throw new IllegalArgumentException("Machine Id can't be greater than " + MAX_MACHINE_ID + " or less than 0");
        }
        this.dataCenterId = dataCenterId;
        this.machineId = machineId;
    }

    /**
     * 生成下一个 ID
     */
    public synchronized long nextId() {
        long currentTimestamp = getCurrentTimestamp();

        // 如果当前时间小于上一次生成 ID 的时间，说明系统时钟被调整过，抛出异常
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - currentTimestamp) + " milliseconds");
        }

        // 如果是同一毫秒内生成的 ID，则对序列号进行递增
        if (currentTimestamp == lastTimestamp) {
            long sequence = this.sequence.getAndIncrement();
            if (sequence > MAX_SEQUENCE) {
                // 序列号溢出，等待下一毫秒
                sequence = waitForNextMillis(lastTimestamp);
            }
            return generateId(currentTimestamp, sequence);
        } else {
            // 不同毫秒，重置序列号为 0
            this.sequence.set(0);
            return generateId(currentTimestamp, 0);
        }
    }

    /**
     * 等待下一毫秒
     */
    private long waitForNextMillis(long lastTimestamp) {
        long timestamp = getCurrentTimestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = getCurrentTimestamp();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳（毫秒）
     */
    private long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }

    /**
     * 生成最终的 ID
     */
    private long generateId(long currentTimestamp, long sequence) {
        this.lastTimestamp = currentTimestamp;
        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT_SHIFT)
                | (dataCenterId << DATA_CENTER_ID_SHIFT)
                | (machineId << MACHINE_ID_SHIFT)
                | sequence;
    }
}
